<?php
/*! \page license
 *
 * Copyright (c) 2011, Blaise Lengrand
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list
 * of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this
 * list of conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.
 * Neither the name of `snWin' nor the names of its contributors may be used to
 * endorse or promote products derived from this software without specific prior
 * written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

  // Initialize the environement
  require_once("../feed.php");

  require_once('system/pages/social/twitter/EpiCurl.php');
  require_once('system/pages/social/twitter/EpiOAuth.php');
  require_once('system/pages/social/twitter/EpiTwitter.php');
  require_once('system/pages/social/twitter/secret.php');

  function twitter_display_name($id, $display_name, $name, $url)
  {
    $str = "";
    if (isset($display_name) && $display_name)
      $str = $display_name;
    else if (isset($name) && $name)
      $str = $name;
    if (isset($url) && $url)
      $str = "<a href=\"".$url."\">".$str."</a>";
    else if (isset($display_name) && $display_name)
      $str = "<a href=\"http://twitter.com/#!/".$display_name."\">".$str."</a>";
    return $str;
  }

  // Make sure the access token are present
  if (!isset($_GET['token']) || !isset($_GET['secret']))
    feed_json_error("No session available");

  // If no action type is specified - screw you!
  if (!isset($_GET['type']))
    feed_json_error("No action type specified");

  // Get user access
  $twitter_obj = new EpiTwitter($consumer_key, $consumer_secret, $_GET['token'], $_GET['secret']);

  $params = array();

  $is_get_method = true;

  switch ($_GET['type'])
  {
  case "update":
    $url = "/statuses/home_timeline.json";
    $params['include_entities'] = 1;
    if (isset($_GET['id']))
      $params['since_id'] = $_GET['id'];
    break;

  case "previous":
    $url = "/statuses/home_timeline.json";
    $params['include_entities'] = 1;
    $params['count'] = 10;
    if (isset($_GET['id']))
      $params['max_id'] = $_GET['id'];
    break;

  case "reply":
    if (isset($_GET['id']))
      $params['in_reply_to_status_id'] = $_GET['id'];
  case "publish":
    $url = "/statuses/update.json";
    if (isset($_GET['message']))
    {
      // Trunc the text
      $tweet = substr($_GET['message'], 0, 140);
      $tweet = iconv("ISO-8859-1", "UTF-8", $tweet);
      $params['status'] = $tweet;
    }
    $is_get_method = false;
    break;

  default:
    feed_json_error("Unknown action type");
  }

  // Send the request
  try
  {
    if ($is_get_method)
      $raw_output = $twitter_obj->get($url, $params);
    else
    {
      $twitter_obj->addHeader("Content-Type: application/x-www-form-urlencoded");
      $twitter_obj->post($url, $params);
    }
  }
  catch (EpiTwitterException $e)
  {
    feed_json_error("Cannot connect to `".$url."' ".$e);
  }
  catch (Exception $e)
  {
    feed_json_error("Cannot connect to `".$url."' ".$e);
  }

  if ($is_get_method)
  {
    // Get the response and parse the feed entries
    $output = json_decode($raw_output->responseText);
    $item = array();
    foreach ($output as $entry)
    {
      $id = ($entry->id_str)?$entry->id_str:number_format($entry->id, 0, '.', '');

      // Name
      $name = "";
      if (isset($entry->user))
        $name = twitter_display_name($id, $entry->user->screen_name, $entry->user->name, $entry->user->url);

      // Link
      $link = "";
      if (isset($entry->entities) && isset($entry->entities->urls) && isset($entry->entities->urls[0]) && isset($entry->entities->urls[0]->url))
        $link = $entry->entities->urls[0]->url;

      // Picture
      $picture = "http://a1.twimg.com/sticky/default_profile_images/default_profile_6_normal.png";
      if (isset($entry->user) && isset($entry->user->profile_image_url))
        $picture = $entry->user->profile_image_url;

      // Message
      $message = "";
      if (isset($entry->text))
        $message = $entry->text;
      $message = preg_replace('/#(\w+)/', '<a href="http://twitter.com/#!/search?q=%23$1">#$1</a>', $message);
      $message = preg_replace('/@(\w+)/', '<a href="http://twitter.com/$1">@$1</a>', $message);

      // Extra
      $extra = array();

      // Twitter->ID & Twitter->Screen_Name & Twitter->Reply_To_ID
      $extra["twitter"] = array(
        "id" => $id,
        "screen_name" => $entry->user->screen_name
      );
      if (isset($entry->in_reply_to_status_id))
        $extra["twitter"]["reply_to_id"] = "twitter_".number_format($entry->in_reply_to_status_id, 0, '.', '');

      // "Name->Tooltip" extra attribute
      if (isset($entry->user->screen_name) && isset($entry->user->name))
      {
        $tooltip = $entry->user->name;
        if (isset($entry->user->description) && $entry->user->description)
          $tooltip .= " - ".$entry->user->description;
        $extra["name"] = array(
          "tooltip" => $tooltip
        );
      }

      // "Source"
      if (isset($entry->source))
      {
        $extra["date_after_text"] = array(
          "text" => " via ".$entry->source
        );
      }

      // "To" extra attribute
      if (isset($entry->in_reply_to_user_id) || isset($entry->in_reply_to_screen_name))
      {
        $to = twitter_display_name($entry->in_reply_to_user_id, $entry->in_reply_to_screen_name, null, null);
        $extra["to"] = $to;
      }

      $item[] = array(
        "id" => "twitter_".$id,
        "name" => $name,
        "picture" => $picture,
        "link" => $link,
        "message" => $message,
        "date" => strtotime($entry->created_at),
        "icon" => "http://twitter.com/phoenix/favicon.ico",
        "extra" => $extra
      );
    }
  }
  else
    $item = null;

  feed_json_success($item);
?>
